package com.rams.jhms.fs;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.rams.jhms.Config;
import com.rams.jhms.fs.xml.XmlWorker;
import com.rams.jhms.l18n.LocalStringsFactory;
import com.rams.jhms.logging.BaseLogger;

public class FSConfigWorker {
	
	private enum configParams {
		local,
		mediaDbPath
	}
	
	public void save() {
		File configFile = new File(Config.configFileName);
		if (configFile.exists() && configFile.canWrite()) {
			configFile.delete();
		} else if (configFile.exists() && !configFile.canWrite()) {
			BaseLogger.info("Can't write config file. Access denied.");
			return;
		}
		try {
			(new XmlWorker()).writeFile(configFile, createXml());
		} catch (IOException e) {
			BaseLogger.error("FSConfigWorker error:", e);
		}
	}
	
	public void load() {
		File configFile = new File(Config.configFileName);
		if (!configFile.exists())
			return;
		
		Document doc = null;
		try {
			doc = (new XmlWorker()).readFile(configFile);
			parseConfig(doc);
		} catch (DocumentException e) {
			BaseLogger.error("FSConfigWorker error:", e);
		}
	}

	private void parseConfig(Document doc) {
		Element root = doc.getRootElement();

		List<Element> elements = root.elements();
		
		for (Element node : elements) {
			switch (configParams.valueOf(node.getName())) {
				case local : 
					Config.local = LocalStringsFactory.getLocal(node.getText());
					break;
				case mediaDbPath :
					Config.mediaDbPath = node.getText();
					break;
			}
		}
	}
	
	private Document createXml() {
		Document doc = DocumentHelper.createDocument();
		
		Element root = doc.addElement("config");
		
		root.addElement(configParams.local.toString()).addText(Config.local.getName());
		root.addElement(configParams.mediaDbPath.toString()).addText(Config.mediaDbPath);
		
		return doc;
	}
}
